import {
  _decorator,
  Component,
  EventTarget,
  Button,
  View,
  Canvas,
  UITransform,
  log,
  Prefab,
  instantiate,
  math,
  Node,
  ScrollView,
} from "cc";
import { request } from "../common/utils";
import { api } from "../common/config/api";
import { itemLabel } from "./itemLabel";
import peony_client from "../common/utils/sdk/peony_client";
import im_client from "../common/utils/sdk/im_client";
import { config } from "../common/config";
const { ccclass, property } = _decorator;
let i = 0;

@ccclass("click")
export class click extends Component {
  @property(Prefab) itemPrefab: Prefab = null;
  // 获取ScrollView组件
  @property(ScrollView) scroll: ScrollView = null;
  start() {}
  update(deltaTime: number) {}

  callback(event: Event, customEventData: string) {
    // 这里 event 是一个 Touch Event 对象，你可以通过 event.target 取到事件的发送节点
    const node = event.target;
    console.log(customEventData); // foobar
    request(api.commonInfo).then(async (res) => {
      if (res && res.code == 0) {
        i++;
        this.addView(JSON.stringify(res));
      }
    });
  }

  addView(data) {
    // 克隆并将节点添加到content中
    const scrollView: any = this.scroll; // 获取ScrollView组件
    const scrollOffset = scrollView.getScrollOffset().y;
    const UI = scrollView.content.getComponent(UITransform); // 获取ScrollView组件
    log(UI.height);
    let itemNode: Node = instantiate(this.itemPrefab);
    if (itemNode) {
      let height = -UI.height;
      let pos = new math.Vec3(0, height, 0);
      itemNode.setPosition(pos);
      const view = itemNode.getComponent(UITransform); // 获取ScrollView组件

      itemNode.parent = scrollView.content;
      UI.height = UI.height + view.height;

      // this.scrollView.content.addChild(itemNode);
      (itemNode.getComponent("itemLabel") as itemLabel).init(height, data);
    }
  }

  socketClick() {
    im_client.getwebsocket(config.socketUrl, { userId: "123456" });
    im_client.onConnectSuccess((data) => {
      this.addView(JSON.stringify(data));
    });
  }
}
